<template>
  <div class="app-container">
    <el-form ref="noticedemandapprovalRef" :model="formData" :rules="rules" label-width="140px">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="立案号" prop="caseId">
            <el-select
              v-model="formData.caseId"
              placeholder="请选择立案号"
              :disabled="disabled || isFlow"
              clearable
              @change="handleCase">
              <el-option v-for="item in numberList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="立案时间" prop="caseDate">
            <el-date-picker
              clearable
              v-model="formData.caseDate"
              type="date"
              :disabled="disabled || isFlow"
              value-format="YYYY-MM-DD"
              placeholder="请选择立案时间"
              style="width: 100%"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="当事人名称" prop="partyName">
            <el-input v-model="formData.partyName" disabled placeholder="请输入当事人名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="法定代表人" prop="legalRepresentative">
            <el-input v-model="formData.legalRepresentative" disabled placeholder="请输入法定代表人" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="工作单位" prop="workUnit">
            <el-input v-model="formData.workUnit" :disabled="disabled || isFlow" placeholder="请输入工作单位" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="职务" prop="position">
            <el-input v-model="formData.position" disabled placeholder="请输入职务" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="统一社会信用代码" prop="creditCode">
            <el-input v-model="formData.creditCode" disabled placeholder="请输入统一社会信用代码" />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="地址/住址" :rules="rules.addressObj" prop="addressObj">
            <locationSelect v-model="formData.addressObj" disabled style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="案由" :rules="rules.caseCause" prop="caseCause">
            <!-- 案由 -->
            <el-input
              v-model="formData.caseCause"
              type="textarea"
              :rows="4"
              readonly
              :disabled="disabled || isFlow"
              placeholder="请选择案由"
              style="cursor: pointer"
              @click="
                () => {
                  getCaseContent('', '1', 'caseCause')
                  showCausePicker = true
                }
              " />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="案件来源" prop="caseSource">
            <el-select
              v-model="formData.caseSource"
              :disabled="disabled"
              placeholder="请选择案件来源"
              :style="{ width: '18vw' }">
              <el-option v-for="item in case_source" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="案件承办人" prop="caseCreateUser">
            <el-input v-model="formData.caseCreateUser" disabled placeholder="请输入案件承办人" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="执法者编号" prop="caseCreateUserNo">
            <el-input v-model="formData.caseCreateUserNo" disabled placeholder="请输入执法者编号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="行政处罚书文号" prop="decisionsNo">
            <el-input v-model="formData.decisionsNo" disabled placeholder="请输入行政处罚书文号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="送达日期" prop="deliveryDate">
            <el-date-picker
              clearable
              v-model="formData.deliveryDate"
              type="date"
              :disabled="disabled"
              value-format="YYYY-MM-DD"
              placeholder="请选择送达日期"
              style="width: 100%"></el-date-picker>
          </el-form-item>
        </el-col>
        <CaseSituation
          ref="caseSituationRef"
          v-model="formData"
          title="简要案情及查处经过"
          :disabled="disabled"
          :isFlow="isFlow"
          :show="'案情说明, 证据证明, 违反条例, 陈述申辩, 处理依据, 处罚执行情况及罚没财物的处置情况'"
          :caseIsEdit="true"
          :stateIsEdit="true"
          :stateDisabled="disabled || isFlow"
          :isEdit="true"
          :penaltyIsEdit="isEdit || isFlow"
          :violationIsEdit="true"
          :reasonDisabled="true" />
        <el-col :span="24">
          <el-form-item label="行政复议行政诉讼情况" prop="reviewLitigation">
            <SmartTextInput
              v-model="formData.reviewLitigation"
              type="textarea"
              :rows="4"
              placeholder="请输入行政复议行政诉讼情况，输入关键词后按Tab键快速补全"
              :min-length="2"
              :disabled="disabled"
              :max-suggestions="5"
              contentType="100" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="承办人意见" prop="handlerOpinion">
            <SmartTextInput
              v-model="formData.handlerOpinion"
              type="textarea"
              :rows="4"
              placeholder="请输入承办人意见，输入关键词后按Tab键快速补全"
              :min-length="2"
              :disabled="disabled"
              :max-suggestions="5"
              contentType="100" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 案由选择弹窗 -->
    <el-dialog v-model="showCausePicker" title="选择案由" width="500px" :before-close="closeCausePicker">
      <el-select
        v-model="formData.caseCauseId"
        clearable
        filterable
        placeholder="请选择案由"
        style="width: 100%"
        @change="selectCaseCause">
        <el-option v-for="(item, index) in caseCauseList" :key="item.id" :label="item.content" :value="item.id" />
      </el-select>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeCausePicker">取消</el-button>
          <el-button type="primary" @click="confirmCaseCause">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance, watch } from 'vue'
import {
  caseclosureapprovalDetail,
  addCaseclosureapproval,
  updateCaseclosureapproval,
  getCaseList,
  getContent,
  submitCaseclosureapproval,
  reviewCaseclosureapproval,
  previewPdf,
} from '@/api/caseClosed/index.js'
import { registrationcaseDetail } from '@/api/filingReview/register'
import { ElMessage } from 'element-plus'
import locationSelect from '@/components/locationSelect/index.vue'
import CaseSituation from '@/components/CaseSituation/index.vue'
import { commontermsGet } from '@/api/filingReview/register.js'
import SmartTextInput from '@/components/SmartTextInput/index.vue'
import { useRouter } from 'vue-router'

const { proxy } = getCurrentInstance()
const { case_source } = proxy.useDict('case_source')
const router = useRouter()

// Props
const props = defineProps({
  id: {
    type: [String, Number],
    default: null,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  isFlow: {
    type: Boolean,
    default: false,
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
})

// Emits
const emit = defineEmits(['handleSubmit'])

// Form data
const formData = ref({
  id: null,
  caseId: null,
  caseNo: null,
  caseDate: null,
  decisionsId: null,
  partyName: null,
  streetOfCompanyAddress: null,
  address: null,
  legalRepresentative: null,
  deliveryDate: null,
  caseCause: null,
  caseCauseId: null,
  decisionsNo: null,
  caseDesc: null,
  evidenceDesc: null,
  violationRegulations: null,
  statementDefense: null,
  handlingBasis: null,
  penaltyEnforcementDisposal: null,
  reviewLitigation: null,
  handlerOpinion: null,
  workUnit: null,
  position: null,
  creditCode: null,
  caseSource: null,
  caseCreateUser: null,
  caseCreateUserNo: null,
  deliveryDate: null,
})
// 自定义校验器：检查拍摄地点是否完整
const validateLocation = (rule, value, callback) => {
  if (!value || !value.streetOfPhotoLocation || !value.photoLocation) {
    callback(new Error('请选择地点'))
  } else {
    callback()
  }
}
// Form validation rules
const rules = {
  caseId: [{ required: true, message: '立案号不能为空', trigger: ['blur', 'change'] }],
  caseDate: [{ required: true, message: '立案时间不能为空', trigger: ['blur', 'change'] }],
  addressObj: [{ required: true, validator: validateLocation, trigger: ['blur', 'change'] }],
  partyName: [{ required: true, message: '当事人名称不能为空', trigger: ['blur', 'change'] }],
  legalRepresentative: [{ required: true, message: '法定代表人不能为空', trigger: ['blur', 'change'] }],
  caseCause: [{ required: true, message: '案由不能为空', trigger: ['blur', 'change'] }],
  decisionsNo: [{ required: true, message: '行政处罚决定书文号不能为空', trigger: ['blur', 'change'] }],
  caseDesc: [{ required: true, message: '案件说明不能为空', trigger: ['blur', 'change'] }],
  evidenceDesc: [{ required: true, message: '证据证明不能为空', trigger: ['blur', 'change'] }],
  violationRegulations: [{ required: true, message: '违反条例不能为空', trigger: ['blur', 'change'] }],
  statementDefense: [{ required: true, message: '陈述申辩不能为空', trigger: ['blur', 'change'] }],
  handlingBasis: [{ required: true, message: '处理依据不能为空', trigger: ['blur', 'change'] }],
  penaltyEnforcementDisposal: [
    { required: true, message: '处罚执行情况及罚没财物的处置情况不能为空', trigger: ['blur', 'change'] },
  ],
  reviewLitigation: [{ required: true, message: '行政复议行政诉讼情况不能为空', trigger: ['blur', 'change'] }],
  handlerOpinion: [{ required: true, message: '承办人意见不能为空', trigger: ['blur', 'change'] }],
  workUnit: [{ required: true, message: '工作单位不能为空', trigger: ['blur', 'change'] }],
  position: [{ required: true, message: '职务不能为空', trigger: ['blur', 'change'] }],
  creditCode: [{ required: true, message: '统一社会信用代码不能为空', trigger: ['blur', 'change'] }],
  caseSource: [{ required: true, message: '案件来源不能为空', trigger: ['blur', 'change'] }],
  caseCreateUser: [{ required: true, message: '案件创建人不能为空', trigger: ['blur', 'change'] }],
  caseCreateUserNo: [{ required: true, message: '案件创建人编号不能为空', trigger: ['blur', 'change'] }],
  deliveryDate: [{ required: true, message: '交货日期不能为空', trigger: ['blur', 'change'] }],
}

// Refs
const noticedemandapprovalRef = ref()

// Methods
const reset = () => {
  formData.value = {
    id: null,
    caseId: null,
    caseNo: null,
    decisionsId: null,
    demandNo: null,
    partyName: null,
    streetOfCompanyAddress: null,
    address: null,
    legalRepresentative: null,
    deliveryDate: null,
    caseCause: null,
    caseCauseId: null,
    decisionsNo: null,
    caseDesc: null,
    evidenceDesc: null,
    violationRegulations: null,
    statementDefense: null,
    handlingBasis: null,
    penaltyEnforcementDisposal: null,
    reviewLitigation: '截止目前，无行政复议，无行政诉讼。',
    handlerOpinion: '此案已办理完毕，申请结案',
    workUnit: null,
    position: null,
    creditCode: null,
    caseSource: null,
    caseCreateUser: null,
    caseCreateUserNo: null,
    deliveryDate: null,
  }
  proxy.resetForm('noticedemandapprovalRef')
}

// Get detail data
const getDetail = async id => {
  reset()
  if (id) {
    try {
      const res = await caseclosureapprovalDetail(id)
      formData.value = res.data
      formData.value.addressObj = {
        photoLocation: res.data.address,
        streetOfPhotoLocation: res.data.streetOfCompanyAddress,
      }
    } catch (error) {
      console.error('获取详情失败:', error)
    }
  }
}

const handleCase = async val => {
  return new Promise(async (resolve, reject) => {
    if (!val) {
      formData.value.caseNo = ''
      formData.value.decisionsId = ''
      formData.value.decisionsNo = ''
      formData.value.partyName = ''
      formData.value.partyId = ''
      formData.value.legalRepresentative = ''
      formData.value.businessType = ''
      formData.value.creditCode = ''
      formData.value.addressObj = {
        photoLocation: '',
        streetOfPhotoLocation: '',
      }
      formData.value.caseDate = ''
      formData.value.workUnit = ''
      formData.value.position = ''
      formData.value.caseCause = ''
      formData.value.caseSource = ''
      formData.value.caseCreateUser = ''
      formData.value.caseCreateUserNo = ''
      formData.value.deliveryDate = ''
      formData.value.caseDesc = ''
      formData.value.evidenceDesc = ''
      formData.value.violationRegulations = ''
      formData.value.statementDefense = ''
      formData.value.handlingBasis = ''
      return
    }
    const res = await registrationcaseDetail(val)
    const { partyName, partyId, legalRepresentative, businessType, streetOfCompanyAddress, address } = res.data
    formData.value.caseNo = res.data.caseNo
    formData.value.partyName = partyName
    formData.value.partyId = partyId
    formData.value.legalRepresentative = legalRepresentative
    formData.value.businessType = businessType
    formData.value.addressObj = {
      photoLocation: address,
      streetOfPhotoLocation: streetOfCompanyAddress,
    }
    const res2 = await getContent(val)
    // formData.value.caseDate = res2.data.caseDate
    // formData.value.decisionsId = res2.data.penaltyDecisionsId
    // formData.value.decisionsNo = res2.data.decisionsNo
    // formData.value.deliveryDate = res2.data.deliveryDate
    for (let key in res2.data) {
      formData.value[key] = res2.data[key]
    }
    if (!props.id) {
      formData.value.penaltyEnforcementDisposal = res2.data.penaltyEnforcementDisposal
      caseSituationRef.value.handleInitInputs('处罚执行情况及罚没财物的处置情况')
    }

    resolve()
  })
}

// 案由 相关 start ==========================================================
const showCausePicker = ref(false)
const caseCauseList = ref([])

const selectCaseCause = val => {
  formData.value.caseCauseId = val
}

const closeCausePicker = () => {
  showCausePicker.value = false
  formData.value.caseCauseId = formData.value.caseCauseId || ''
}

const confirmCaseCause = () => {
  // 案由选中
  if (formData.value.caseCauseId === undefined) {
    formData.value.caseCauseId = ''
    formData.value.caseCause = ''
    return
  }
  formData.value.caseCause = caseCauseList.value.find(i => i.id === formData.value.caseCauseId)?.content || ''
  showCausePicker.value = false
}

async function getCaseContent(parentType, type, field) {
  const res = await commontermsGet({
    termType: type,
    pageSize: 9999,
    pageNum: 1,
    status: 0,
    parentId: parentType,
  })
  caseCauseList.value = res.data
  formData.value[field] = res.data[0].content
}

// 案由 相关 end ==========================================================

const handlePreview = () => {
  return new Promise(resolve => {
    submitForm(false, true)
      .then(async params => {
        previewPdf(params)
          .then(res => {
            if (!!res.msg) {
              window.open(res.msg)
              resolve()
            } else {
              ElMessage.warning('预览文件不存在')
              resolve()
            }
          })
          .catch(() => {
            ElMessage.warning('预览文件不存在')
            resolve()
          })
      })
      .catch(() => {
        ElMessage.warning('请先完善表单信息')
        resolve()
      })
  })
}

// Submit form
const caseSituationRef = ref(null)
const submitForm = (isDraft = false, isPreview = false) => {
  return new Promise((resolve, reject) => {
    noticedemandapprovalRef.value
      .validate()
      .then(async () => {
        let num = 0
        caseSituationRef.value.penaltyEnforcementDisposalSegments.forEach(item => {
          if (item.type === 'input' && !item.value) {
            num += 1
          }
        })
        if (num > 0 && !props.isEdit) {
          ElMessage.error('请将处罚执行情况及罚没财物的处置情况填写完整')
          reject()
          return false
        }
        formData.value.address = formData.value.addressObj.photoLocation
        formData.value.streetOfCompanyAddress = formData.value.addressObj.streetOfPhotoLocation
        if (isPreview === true) {
          resolve({ ...formData.value })
          return
        }
        let result
        if (isDraft) {
          // 草稿
          if (formData.value.id) {
            result = await updateCaseclosureapproval(formData.value)
          } else {
            result = await addCaseclosureapproval(formData.value)
          }
        } else {
          // 提交
          result = await submitCaseclosureapproval(formData.value)
        }

        ElMessage.success('提交成功')
        emit('handleSubmit', result)
        return result
      })
      .catch(error => {
        reject(error)
      })
  })
}

// 待办页面 提交 / 退回
const handleSubmitReview = async form => {
  await reviewCaseclosureapproval({
    ...form,
    id: props.editId || props.id,
  })
  proxy.$modal.msgSuccess('操作成功')
  router.back()
}

// 待办页面获取批注列表
const timer = ref(null)
const getAnnotationList = () => {
  return new Promise((resolve, reject) => {
    timer.value = setInterval(() => {
      if (formData.value.id) {
        clearInterval(timer.value)
        resolve({ ...formData.value })
      } else {
        resolve([])
      }
    }, 500)
  })
}

// Watch props.id change
watch(
  () => props.id,
  newVal => {
    if (newVal) {
      getDetail(newVal)
    } else {
      reset()
    }
    handleCaseList()
  },
  { immediate: true }
)

const numberList = ref([])
async function handleCaseList() {
  const res = await getCaseList()
  numberList.value = res.data.map(item => ({
    label: item.caseNo,
    value: item.id,
  }))
}

onMounted(() => {
  nextTick(() => {
    caseSituationRef.value.handleInitInputs2()
  })
})
// Expose methods
defineExpose({
  submitForm,
  handlePreview,
  reset,
  formData,
  handleSubmitReview,
  getAnnotationList,
  formRef: noticedemandapprovalRef,
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>
